

window.console = window.console ||
{
    log: function(){
        opera.postError(arguments);
    }
};

function log(){
    console.log.apply(null, arguments)
}

Array.prototype.findAll = function(_function, context){
    var results = [];
    for (var i = 0, l = this.length; i < l; i++) {
        if (_function.call(context, this[i], i)) 
            results.push(this[i]);
    }
    return results;
}


Array.prototype.inArray = function(p_val){
    return this.indexOf(p_val) > -1;
}

File.prototype.readBase64 = function(){
    var strm, content = '';
    try {
        strm = this.open(null, opera.io.filemode.READ);
        content = strm.readBase64(strm.bytesAvailable, 'UTF-8');
        strm.close();
        return content;
    } 
    catch (e) {
        opera.postError(e);
        return false;
    };
    };

File.prototype.readContent = function(bytes){
    var strm, content = '';
    try {
        strm = this.open(null, opera.io.filemode.READ);
        content = strm.read(bytes || strm.bytesAvailable, 'UTF-8');
        strm.close();
        return content;
    } 
    catch (e) {
        opera.postError(e);
        return false;
    };
    };

File.prototype.writeBase64 = function(content){
    var strm;
    try {
        //	console.log("readonly" + this.readOnly);
        strm = this.open(null, opera.io.filemode.WRITE);
        strm.writeBase64(content);
        strm.close();
        return true;
    } 
    catch (e) {
        opera.postError(e);
        return false
    };
    };

File.prototype.writeContent = function(content){
    var strm;
    try {
        strm = this.open(null, opera.io.filemode.WRITE);
        strm.write(content);
        strm.close();
        return true;
    }
    catch (e) {
        opera.postError(e);
        return false
    };
    };

String.prototype.startsWith = function(str){
    return (this.match("^" + str) == str)
}

/**
 * Formats serialized xml to readable form
 * @param {Object} xml object
 * @return {String}
 * @author Michał Borek
 */
XMLSerializer.prototype.serializeToFormattedString = function(xml){
    var xml = this.serializeToString(xml);
    var result = "";
    var reg = /(>)(<)(\/*)/g;
    xml = xml.replace(reg, '$1\r\n$2$3');
    var rows = xml.split("\r\n");
    var level = 0;
    var intend = 0;
    var space;
    for (var i = 0; i < rows.length; i++) {
        if ((/<\w[^>\/]*>$/).exec(rows[i])) { // <node> rows[i].match(/<\w[^>\/]*>$/)
            level = 1;
        }
        else 
            if ((/^<\/\w/).exec(rows[i])) { // </node>
                level = 0;
                intend -= 1;
            }
            else 
                if ((/<\w[^>]*\/>$/).exec(rows[i]) || (/^<\w[^>]*>[^<]*<\/\w[^>]*>$/).exec(rows[i])) {
                    level = 0;
                }
        space = "";
        for (var j = 0; j < intend; j++) {
            space += '\t';
        }
        result += space + rows[i] + '\r\n';
        intend += level;
    }
    return result;
}

